package cn.lb.org.service.impl;

import cn.lb.basic.service.impl.BaseServiceImpl;
import cn.lb.org.domain.Department;
import cn.lb.org.mapper.DepartmentMapper;
import cn.lb.org.query.DepartmentQuery;
import cn.lb.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;
    @Transactional
    public void insert(Department department) {
        department.setCreate_time(new Date());
        departmentMapper.insert(department);
        Department parent = department.getParent();
        String path="";
        if(Objects.isNull(parent)|| parent.getId()==null){
            path="/"+department.getId();
        }else {
            Department department1 = departmentMapper.selectById(parent.getId());
            path=department1.getPath()+"/"+department.getId();
        }
        department.setPath(path);
        departmentMapper.update(department);
    }

    @Transactional
    public void deleteById(Serializable id) {
departmentMapper.deleteById(id);
    }


    @Transactional
    public void update(Department department) {
        department.setUpdate_time(new Date());
        Department parent = department.getParent();
        String path="";
        if(Objects.isNull(parent)|| parent.getId()==null){
            path="/"+department.getId();
        }else {
            Department department1 = departmentMapper.selectById(parent.getId());
            path=department1.getPath()+"/"+department.getId();
        }
        department.setPath(path);
        departmentMapper.update(department);
    }



    @Override
    public List<Department> trees() {
        System.out.println(1);
        List<Department> tree = departmentMapper.tree();
        System.out.println(tree);
        return tree;
    }
}
